package org.github.choviwu.example.common.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.github.choviwu.example.common.annatation.JsonController;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对请求的Json加解密
 */
@RestControllerAdvice(basePackages = "org.choviwu")
public class ResultResponse implements ResponseBodyAdvice<Object> {

    private String key = "1fdsv3choviwu@#~";

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    /**
     * 加密Json
     * @param o  加密的Json
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //是否加密Json
        if(methodParameter.getMethod().isAnnotationPresent(JsonController.class)){
            JsonController jsonController = methodParameter.getMethod().getAnnotation(JsonController.class);
            //如果加密
            if(jsonController.encode()){
                //TODO
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                   String result =  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
                   //result =  AESUtil.getInstance().encrypt(result,key);//加密
                    return result;
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }

        return o;
    }
}
